package org.example.workbench.controller;

import org.example.commons.constant.Constant;
import org.example.commons.domain.ErrorInfo;
import org.example.settings.domain.DictionaryValue;
import org.example.settings.domain.User;
import org.example.settings.mapper.DictionaryValueMapper;
import org.example.settings.mapper.UserMapper;
import org.example.settings.service.DictionaryValueService;
import org.example.settings.service.UserService;
import org.example.workbench.domain.Tran;
import org.example.workbench.domain.TranHistory;
import org.example.workbench.domain.TranRemark;
import org.example.workbench.mapper.TranMapper;
import org.example.workbench.service.CustomerService;
import org.example.workbench.service.TranHistroyService;
import org.example.workbench.service.TranRemarkService;
import org.example.workbench.service.TranService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Controller
@RequestMapping("/tran")
public class tranController {

    @Autowired
    private DictionaryValueService dictionaryValueService;
    @Autowired
    private UserService userService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private TranService tranService;
    @Autowired
    private TranRemarkService tranRemarkService;
    @Autowired
    private TranHistroyService tranHistroyService;

    @RequestMapping("/getTranPagesByMap")
    public @ResponseBody Object getTranPagesByMap(@RequestParam Map<String,Object> map){
        int currentPage = Integer.parseInt((String) map.get("currentPage"));
        int pageSize = Integer.parseInt((String) map.get("pageSize"));
        int pageNo=(currentPage-1)*pageSize;
        map.put("pageSize",pageSize);
        map.put("pageNo",pageNo);
        List<Tran> tranList = tranService.getTranPagesByMap(map);
        int totalCount = tranService.getTotalCountTran(map);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("tranList",tranList);
        hashMap.put("totalCount",totalCount);
        return hashMap;
    }
    @RequestMapping("/deleteTranById")
    public @ResponseBody Object deleteTranById(String tranId){
        ErrorInfo errorInfo = new ErrorInfo();
        try{
            int i = tranService.deleteTranById(tranId);
            if (i>0){
                errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_SUCCESS);
            }else{
                errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
                errorInfo.setErrorMessage("系统繁忙。请稍后......");
            }
        }catch (Exception e){
            errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
            errorInfo.setErrorMessage("系统繁忙。请稍后......");
        }
        return errorInfo;
    }
    @RequestMapping("/getDetailTran")
    public String getDetailTran(String id,HttpServletRequest request){
        Tran tran = tranService.getTranDetailByid(id);
        List<TranRemark> tranRemarkList = tranRemarkService.getTranRemarksByTranId(id);
        List<TranHistory> tranHistoryList = tranHistroyService.getTranHistoriesByTranId(id);
        ResourceBundle bundle = ResourceBundle.getBundle("possibility", Locale.getDefault(), new ResourceBundle.Control() {
            @Override
            public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException {
                // 使用 UTF-8 编码加载 properties 文件
                String bundleName = toBundleName(baseName, locale);
                String resourceName = toResourceName(bundleName, "properties");
                try (InputStream stream = loader.getResourceAsStream(resourceName)) {
                    return new PropertyResourceBundle(new InputStreamReader(stream, StandardCharsets.UTF_8));
                }
            }
        });
        String possibility = bundle.getString(tran.getStage());
        request.setAttribute("tran",tran);
        request.setAttribute("tranRemarkList",tranRemarkList);
        request.setAttribute("tranHistoryList",tranHistoryList);
        request.setAttribute("possibility",possibility);
        //查询所有阶段
        List<DictionaryValue> stageList = dictionaryValueService.selectDicValueByType("stage");
        //查询当前阶段的order_no的值
        String orderNo = dictionaryValueService.getOrderNoByStageValue(tran.getStage());
        request.setAttribute("stageList",stageList);
        request.setAttribute("orderNo",orderNo);
        return "workbench/transaction/detail";
    }
    @RequestMapping("/saveTran")
    public @ResponseBody Object saveTran(@RequestParam Map<String,Object> map, HttpSession session){
        User user =(User) session.getAttribute(Constant.SESSION_USER);
        map.put(Constant.SESSION_USER,user);
        ErrorInfo errorInfo = new ErrorInfo();
        try{
            tranService.saveTran(map);
            errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_SUCCESS);
        }catch (Exception e){
            errorInfo.setErrorCode(Constant.ERROR_INFO_CODE_FAIL);
            errorInfo.setErrorMessage("系统繁忙。请稍后......");
        }
        return errorInfo;
    }

    @RequestMapping("/getCustomerNameByName")
    @ResponseBody
    public Object getCustomerNameByName(String name){
        System.out.println(customerService.getCustomerByName(name));
        return customerService.getCustomerByName(name);
    }

    @RequestMapping("/getPossibilityStage")
    @ResponseBody
    public Object getPossibilityStage(String stage){
        //因为 ResourceBundle 类默认使用 ISO-8859-1 编码来处理 properties 文件中的键值对。
        //为了能够正确获取使用中文汉字作为键的属性值,必须重写方法
        ResourceBundle bundle = ResourceBundle.getBundle("possibility", Locale.getDefault(), new ResourceBundle.Control() {
            @Override
            public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException {
                // 使用 UTF-8 编码加载 properties 文件
                String bundleName = toBundleName(baseName, locale);
                String resourceName = toResourceName(bundleName, "properties");
                try (InputStream stream = loader.getResourceAsStream(resourceName)) {
                    return new PropertyResourceBundle(new InputStreamReader(stream, StandardCharsets.UTF_8));
                }
            }
        });
        return bundle.getString(stage);
    }

    @RequestMapping("/toSaveJsp")
    public String toSaveJsp(HttpServletRequest request){
        List<User> userList = userService.findAll();
        List<DictionaryValue> stageList = dictionaryValueService.selectDicValueByType(Constant.STAGE);
        List<DictionaryValue> tranList = dictionaryValueService.selectDicValueByType(Constant.TRANSACTION_TYPE);
        List<DictionaryValue> sourceList = dictionaryValueService.selectDicValueByType(Constant.SOURCE);
        request.setAttribute("userList",userList);
        request.setAttribute("stageList",stageList);
        request.setAttribute("tranList",tranList);
        request.setAttribute("sourceList",sourceList);
        return "workbench/transaction/save";
    }
    @RequestMapping("/index")
    public String index(HttpServletRequest request){
        List<DictionaryValue> stageList = dictionaryValueService.selectDicValueByType(Constant.STAGE);
        List<DictionaryValue> tranList = dictionaryValueService.selectDicValueByType(Constant.TRANSACTION_TYPE);
        List<DictionaryValue> sourceList = dictionaryValueService.selectDicValueByType(Constant.SOURCE);
        request.setAttribute("stageList",stageList);
        request.setAttribute("tranList",tranList);
        request.setAttribute("sourceList",sourceList);
        return "workbench/transaction/index";
    }
}
